<?php
/*
 * $Id: ExampleProtocol.php,v 1.5 2009-04-19 13:42:59 root Exp $
 */
require_once(realpath(dirname(__FILE__)).'/SocketServer.php');

class MyProtocol extends tSocketProtocol{
	public $MySQLResource;
	public $UserVar;
	public $DeckVar;
	public $SessionVar;
    public $SessionInfoStorage;
    
	function Write64($Connection, $Data) {
		$this->WriteTo($Connection->id, base64_encode($Data));
	}
	
	function WriteToAll64($Data) {
		$this->WriteToAll(base64_encode($Data));
	}
	
	function DecodeClientData($Data) {
		$JSON = json_decode($Data, $true);
		return $JSON;
	}
	
	function onConnect($Connection){
		$this->Write64($Connection->id, json_encode(array("server-response"=>"authrequest", "connection-id"=>$Connection->id))."\r\n");
	}
	function onDisconnect($Connection){
		if($UserVar[$Connection->id]['logged-in'] = True) {
		$this->WriteToAll64(json_encode(array("server-response"=>"disconnect-user","username"=>$UserVar[$Connection->Id]['UserObj']->Username,"connectionid")));
		}
	}
	
	function UserARP($Connection,$Username) {
		$this->WriteToAll64(json_encode(array("server-response"=>"URP","Username"=>$Username,"connection-id"=>$Connection->id)));
	}
	
	function RespondToClient($ConnectionIDTo, $Data) {
		$this->Write64($ConnectionIDTo, json_encode($data));
	}
	
	function onData($Connection){
		// Найдем позицию разделителя
		$p = strpos(base64_decode($Connection->ReadBUF, "\n"));
		if ($p === false) return;
		// Вырежем команду
		$cmd = substr(base64_decode($Connection->ReadBUF,0,$p));
		$Connection->ReadBUF = substr(base64_decode($Connection->ReadBUF, $p+1));
        $cmd = json_decode($cmd);
		switch ($cmd['client-response']) {
			case "disconnect-user":
				$This->ConnectionManager->detach($Connection);
				break;
			case "authorize-user":
				$Username = mysql_escape_string($cmd['username']);
				$Password = mysql_escape_string($cmd['password']);
				$SessionQuery = mysql_query("SELECT * FROM Users WHERE username = '".$Username."' and password = '".$Password."';");
				if(!mysql_fetch_assoc($SessionQuery)) {
					$this->Write64($Connection->id, json_encode(array("server-response"=>'unauthorized',"reason"=>"bad username or password")));
				} else {
					$UserVar[$Connection->id]['UserObj'] = mysql_fetch_object($SessionQuery);
					$UserVar[$Connection->id]['logged-in'] = true;
					$SendToClient = array("server-response"=>'logged-in','connection-id'=>$Connection->id,'Username'=>$UserVar[$Connection->id]['UserObj']->Username,'DeckSecurityCode'=>$UserVar[$Connection->id]['UserObj']->DeckCreatorSecCode);
					$SendToAll = array("server-response"=>'player-login','Username'=>$Username);
					$this->Write64($connection->id, $SendToClient);
					$this->WriteToAll64($SendToAll);
				}
				break;
			case "get-user-connection-id":
				UserARP($Connection->id, $Username);
				break;
			case "reply-user-arp":
				RespondToClient($cmd['reply-id'],json_encode(array("server-response"=>"resolve-user-arp", "connection-id"=>$Connection->id)));
				break;
			case "challenge-user":
				$this->Write64($cmd['user-id'],json_encode(array("server-response"=>'user-challenge','challenger'=>$Connection->id,'ChallengerUser'=>$UserVar[$Connection->id]['UserObj']->Username)));
				break;
			case "challenge-accept":
				$this->Write64($cmd['user-id'],json_encode(array("server-response"=>'accept-challenge')));
				$SessionVar[$Connection->ID]['Battle']['OpponentID'] = $cmd['user-id'];
                $SessionInfoCount = count($SessionInfoStorage);
                ++$SessionInfoCount;
                $SessionVar[$Connection->ID]['Battle']['SessionID'] = $SessionInfoCount; 
                $SessionInfoStorage[$SessionInfoCount] = ZVTCGEngine::CreateSessionInfo(Array("User-ConnectionID"=>$Connection->id, "Opponent-ConnectionID"=>$SessionVar[$Connection->ID]['Battle']['OpponentID'],"UserObj"=>$UserObj[$Connection-ID],"OpponentObj"=>$UserObj[$SessionVar[$Connection->ID]],"UserVar"=>$UserVar));
                break;
			case "challenge-deny":
				$this->Write64($cmd['user-id'],json_encode(array("server-response"=>'deny-challenge')));
				break;
			case "startSession":
				//$this->Write64($Connection->id,json_encode(array("server-response"=>'startSession','User1'=>array('Username'=>$UserVar[$cmd['username']]['UserObj']->Username //Start on this after getting the deck creation code done.
				break;
			case "joinSession":
				//Other player Joins session
				break;
			case "syncSession":
				//Synchronize the Session's Gameboard.
				break;
			case "endSession":
				//End the session, applying battle rankings and rewards.
			case "doAction":
				//preform various actions based on the command.
	        case "deckShuffle":
                $CurrentDeck = explode(",",$UserVar[$Connection->id]['UserObj']->Deck);
                $i = 50;
                $x;
                while($x <> 50) {
                    $RandomCard = rand(0, $i);
                    if(array_key_exists($CurrentDeck[$RandomCard])) {
                        $ShuffledDeck[$x] = $CurrentDeck[$RandomCard];
                        unset($CurrentDeck[$RandomCard]);
                        $CurrentDeck = array_values($CurrentDeck);
                        --$i;
                         ++$x;
                    }
                }
                $DeckVar[$Connection->id]['Deck'] = $ShuffledDeck;
                break;
            case "Skill":
                    ZVTCGEngine::UseSkill();
                    break;
            }
        }
    }
class TestHTTPProtocol extends tSocketProtocol{
	function onData($Connection){
		$Connection->Write("HTTP/1.1 200 OK\r\nContenth-type: text/html; charset=UTF-8\r\n\r\nOK");
		$Connection->Close();
	}
}

$server = new tSocketServer();
$server->attachProtocol(new MyProtocol());
// accepting connections on port 4111 and 4112
if ($server->Bind('127.0.0.1', 4111)){
	if ($server->Bind('127.0.0.1', 4112)){
		echo "Binded\n";
		$server->Start();
	}
}

?>